package com.wangrui.test;

import java.io.IOException;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;

import com.wangrui.entity.User;

public class MyBatisTest09 {

    /**
     * 获得MyBatis SqlSessionFactory
     * SqlSessionFactory负责创建SqlSession，一旦创建成功，就可以用SqlSession实例来执行映射语句
     * ，commit，rollback，close等方法。
     *
     * @return
     */
    private static SqlSessionFactory getSessionFactory() {
        SqlSessionFactory sessionFactory = null;
        String resource = "configuration.xml";
        try {
            sessionFactory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsReader(resource));
        } catch (IOException e) {

            e.printStackTrace();
        }
        return sessionFactory;
    }


    @Test
    public void testCache1() {
        SqlSessionFactory factory = getSessionFactory();
        SqlSession session = factory.openSession();
        User user = session.selectOne("com.wangrui.myBatis.UserMapper9.getUser", 1);
        session.clearCache();
        user = session.selectOne("com.wangrui.myBatis.UserMapper9.getUser", 1);
        session.close();
    }

    /**
     * 使用缓存
     */
    @Test
    public void testCache2() {
        SqlSessionFactory factory = getSessionFactory();
        SqlSession session = factory.openSession();
        User user = session.selectOne("com.wangrui.myBatis.UserMapper9.getUser", 1);
        System.out.println("第一次查询，name:" + user.getName());
        session.close();//只有session关闭之后，缓存才会从一级缓存转移到二级缓存中
        System.out.println("关闭session，重新打开session");
        SqlSession session2 = factory.openSession();
        user = session2.selectOne("com.wangrui.myBatis.UserMapper9.getUser", 1);
        System.out.println("第一次查询,从二级缓存中取，没有查数据库，name:" + user.getName());
        session.close();
        session2.close();
    }

}
